package com.deyuanyun.pic.settings.support.shiro;

import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  目前添加的目的是为了解决用户在一个页面退出过后，在没有执行退出的页面中执行ajax请求的时候没有对应的已经退出提醒，
 *  故加上已经退出标记，方便前台来判断用户是否已经退出，来决定是否刷新页面。
 *
 *  这个类以后可以扩展一下来做用户登录的验证码、自定义登录成功登录失败的方法、shiro异常处理等等
 *
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-07-22
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log  = LoggerFactory.getLogger(CustomFormAuthenticationFilter.class);


    /**
     * 拒绝访问的时候调用的方法
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        if (!isLoginRequest(request, response)) { //不是登录请求
            String ajaxMode = httpServletRequest.getParameter("AjaxMode");//项目是根据AjaxMode参数来判断是不是ajax请求的，
            if (StringUtils.isEmpty(ajaxMode)) {// 为空一律视为不是ajax请求
                return super.onAccessDenied(request, response); //交给父类的方法处理
            } else { //是ajax请求的时候返回json数据
                AjaxSupport.sendFailText("sessionStatusFalse", "未登录或者已过期");
            }
            return false;
        } else { //是登录请求
            return super.onAccessDenied(request, response); //交给父类的方法处理
        }

    }

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        super.redirectToLogin(request, response);
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        /* 让shiro来往RequestResponseContext中保存request，response到当前线程中，
         shiro在spring mvc之前所以，spring mvc不再需要往RequestResponseContext中保存request，response到当前线程*/
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        RequestResponseContext.setRequest(httpServletRequest);
        RequestResponseContext.setResponse(httpServletResponse);
        return super.preHandle(request, response);
    }

}
